import re
import sys,os
sys.path.append(os.path.join(os.getcwd()))

from framework.frontend.speech_client import fallback_tts
from tool.config.config import get_config
from framework.frontend.recoder import VoiceRecorder
from framework.frontend.command import Commander
from multiprocessing import Process
from audioBot.cmd_executors import chat
from audioBot.cmd_executors import summerize
import sounddevice as sd
import soundfile as sf
import time

def say_sth(text):
    fallback_tts(text,"./tmp.wav")
    data, samplerate = sf.read("./tmp.wav", dtype='float32')  # 读取音频数据
    sd.play(data, samplerate)  # 播放
    sd.wait()  # 等待播放结束

cmd_executor = {
    r"开\s*始\s*聊\s*天.*": chat.chat_executor,
    r"总\s*结\s*学\s*习\s*状\s*态.*": summerize.summerize_executor
}

def record_loop():
    commander = Commander()
    recorder = VoiceRecorder()
    print(f"sleep words:{get_config('sys.toml')['AUDIO']['WAKE_WORDS']}")
    for cmd,exec in cmd_executor.items():
        print(f"cmd:{cmd}")
    # say_sth("比特灵犀已启动，请访问对应的后台管理站点，查看相关配置")
    while True:
        recorder.start_recording()
        print(f"Recorder started with config: {recorder.query_text}")
        if commander.match_cmd(recorder.query_text,get_config("sys.toml")["AUDIO"]["WAKE_WORDS"]):
            say_sth("你好，我是小智，一个智能教学语音助手")
            while True:
                print("Wake word detected!")
                recorder.start_recording()
                print(f"recording: {repr(recorder.query_text)}")
                if not recorder.query_text:
                    continue
                if commander.match_cmd(recorder.query_text,get_config("sys.toml")["AUDIO"]["SLEEP_WORDS"]):
                    print("Sleep word detected! Stopping recording.")
                    break
                else:
                    print("Processing command...")
                    for cmd,executor in cmd_executor.items():
                        print(f"query_text:{recorder.query_text},cmd:{cmd}")
                        if re.fullmatch(cmd,recorder.query_text):
                            print(f"trigger cmd:{cmd}")
                            executor(recorder)
        # time.sleep(1)  # 防止疯狂刷屏，可以设置为录音间隔或持续时间

def wait_speak():
    """
    Wait for the user to speak and start recording.
    """
    # record_loop()
    p = Process(target=record_loop)
    p.start()
if __name__ == "__main__":
    wait_speak()  # 启动录音监听
    while True:
        time.sleep(1)  # 保持主进程运行，防止退出